package com.alander.nexusgo.im.netty.codec;

import com.alander.nexusgo.im.constants.ImConstants;
import com.alander.nexusgo.im.model.dto.ImMsg;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class ImMessageDecoder extends ByteToMessageDecoder {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(ImMessageDecoder.class);
    
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        // 检查是否有足够的数据读取头部（short magic + int code + int len = 10字节）
        if (in.readableBytes() < 10) {
            return;
        }
        
        // 标记当前读位置
        in.markReaderIndex();
        
        // 读取魔数
        short magic = in.readShort();
        if (magic != ImConstants.DEFAULT_MAGIC) {
            LOGGER.warn("非法的魔数: {}", magic);
            ctx.close();
            return;
        }
        
        // 读取消息代码和长度
        int code = in.readInt();
        int len = in.readInt();
        
        // 检查是否有足够的数据读取body
        if (in.readableBytes() < len) {
            // 重置读位置，等待更多数据
            in.resetReaderIndex();
            return;
        }
        
        // 读取body数据
        byte[] body = new byte[len];
        in.readBytes(body);
        
        // 创建消息对象
        ImMsg imMsg = new ImMsg();
        imMsg.setMagic(magic);
        imMsg.setCode(code);
        imMsg.setLen(len);
        imMsg.setBody(body);
        
        // 添加到输出列表
        out.add(imMsg);
    }
}